<template>
  <div class="review-container">
    <!-- 顶部导航栏 -->
    <div class="navbar">
      <router-link :to="{ name: 'orders' }" class="navbar-back">
        <i class="fas fa-arrow-left"></i>
      </router-link>
      <div class="navbar-title">评价商品</div>
      <div></div>
    </div>

    <!-- 店铺信息 -->
    <div class="store-info">
      <i class="fas fa-store store-icon"></i>
      <span>{{ orderInfo.storeName }}</span>
    </div>

    <!-- 商品信息 -->
    <div class="product-container">
      <div class="product-card" v-for="(product, index) in orderInfo.products" :key="index">
        <img class="product-image" :src="product.mainImage" :alt="product.name">
        <div class="product-details">
          <div class="product-name">{{ product.name }}</div>
          <div class="product-attr">{{ product.attributes }}</div>
          <div class="product-price-qty">
            <span class="price">¥{{ product.price }}</span>
            <span class="quantity">x{{ product.quantity }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 综合评分 -->
    <div class="service-rating">
      <div class="service-title">综合评分</div>
      <div class="rating-stars">
        <i v-for="i in 5" :key="i" class="fas fa-star" :class="{ 'active': i <= averageRating }"></i>
        <div class="rating-text">{{ averageRating }} 星</div>
      </div>
    </div>

    <!-- 评分 -->
    <div class="rating-container">
      <div class="rating-header">商品评分</div>
      <div class="rating-stars">
        <i v-for="i in 5" :key="i" class="fas fa-star" :class="{ 'active': i <= rating }" @click="setRating(i)"></i>
        <div class="rating-text">{{ getRatingText() }}</div>
      </div>
    </div>

    <!-- 物流服务评分 -->
    <div class="service-rating">
      <div class="service-title">物流服务</div>
      <div class="service-stars">
        <i v-for="i in 5" :key="i" class="fas fa-star" :class="{ 'active': i <= logisticsRating }"
          @click="logisticsRating = i"></i>
      </div>
    </div>

    <!-- 商家服务评分 -->
    <div class="service-rating">
      <div class="service-title">商家服务</div>
      <div class="service-stars">
        <i v-for="i in 5" :key="i" class="fas fa-star" :class="{ 'active': i <= sellerRating }"
          @click="sellerRating = i"></i>
      </div>
    </div>

    <!-- 评价内容 -->
    <div class="review-content">
      <div class="content-header">评价内容</div>
      <textarea class="content-textarea" v-model="content" placeholder="请分享您的购买体验、使用心得或您关注的问题（最少5个字，最多500个字）"
        :maxlength="500"></textarea>
      <div class="content-count">{{ content.length }}/500</div>
    </div>

    <!-- 上传图片 -->
    <div class="upload-container">
      <div class="upload-header">上传图片 (选填)</div>
      <div class="upload-grid">
        <div v-for="(img, index) in images" :key="index" class="image-item">
          <img :src="img" class="preview-image">
          <div class="delete-btn" @click="deleteImage(index)">
            <i class="fas fa-times"></i>
          </div>
        </div>
        <div class="upload-btn" v-if="images.length < 5" @click="uploadImage">
          <i class="fas fa-camera"></i>
          <div class="upload-text">添加图片</div>
        </div>
      </div>
      <div class="upload-tip">最多上传5张图片</div>

      <!-- 隐藏的文件输入 -->
      <input type="file" ref="fileInput" accept="image/*" style="display: none" @change="handleFileChange" />
    </div>

    <!-- 匿名评价 -->
    <div class="anonymous-container">
      <div class="anonymous-switch">
        <span>匿名评价</span>
        <label class="switch">
          <input type="checkbox" v-model="isAnonymous">
          <span class="slider"></span>
        </label>
      </div>
      <div class="anonymous-tip">开启后，评价中将隐藏您的用户名信息</div>
    </div>

    <!-- 提交按钮 -->
    <div class="submit-container">
      <button class="submit-btn" @click="submitReview" :disabled="!isReviewValid">提交评价</button>
    </div>
  </div>
</template>

<script>
import { defineComponent, ref, computed, onMounted, onBeforeUnmount } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { showToast, showDialog } from 'vant';
import api from '@/network/api';

export default defineComponent({
  name: 'OrderReviewView',
  setup() {
    const route = useRoute();
    const router = useRouter();
    const orderId = route.query.orderId;
    const productId = route.query.productId; // 从路由参数获取商品ID
    const orderItemId = route.query.orderItemId; // 从路由参数获取订单项ID

    // 保存定时器引用，用于清理
    let redirectTimer = null;

    // 基本数据
    const rating = ref(5); // 默认5星
    const logisticsRating = ref(5);
    const sellerRating = ref(5);
    const content = ref('');
    const images = ref([]);
    const isAnonymous = ref(false);
    const hasReviewed = ref(false); // 用于标记是否已评价

    // 计算平均分
    const averageRating = computed(() => {
      return Math.floor((rating.value + logisticsRating.value + sellerRating.value) / 3);
    });

    // 模拟订单数据
    const orderInfo = ref({
      orderId: orderId,
      storeName: '爱宠天地',
      products: [
        {
          id: 301,
          name: '舒适保暖宠物窝 可拆洗 适合中小型犬',
          attributes: '灰色',
          price: 199,
          quantity: 1,
          image: 'https://images.unsplash.com/photo-1551717743-49959800b1f6?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=60'
        }
      ]
    });

    // 获取订单详情
    const fetchOrderDetail = async () => {
      try {
        // 调用API获取订单详情
        const response = await api.getOrderDetail(Number(orderId));
        if (response && response.code === 100) {
          const orderData = response.data;

          // 调试输出
          console.log('订单详情数据:', orderData);

          // 检查对应商品是否已评价
          if (orderData.orderItems && Array.isArray(orderData.orderItems)) {
            const orderItem = orderData.orderItems.find(item =>
              (productId && item.productId == productId) ||
              (orderItemId && item.orderItemId == orderItemId)
            );

            if (orderItem && orderItem.isReviewed === 1) {
              showToast('该商品已评价');
              // 延迟返回订单列表
              setTimeout(() => {
                router.replace('/orders');
              }, 1500);
              return;
            }
          }

          // 检查是否已评价过
          if (orderData.productReviews && Array.isArray(orderData.productReviews)) {
            const reviewed = orderData.productReviews.some(review =>
              review.productId == productId || review.orderId == orderId
            );

            if (reviewed) {
              hasReviewed.value = true;
              showToast('该商品已评价');
              // 延迟返回订单列表
              setTimeout(() => {
                router.replace('/orders');
              }, 1500);
              return;
            }
          }

          // 查找当前要评价的商品信息
          let targetProduct = null;

          if (productId && orderData.productsItems) {
            // 从productsItems中查找目标商品
            targetProduct = orderData.productsItems.find(item => item.productId == productId);
          }

          if (!targetProduct && orderData.orderItems) {
            // 从orderItems中查找目标商品
            const orderItem = orderData.orderItems.find(item => item.productId == productId);
            if (orderItem) {
              targetProduct = {
                id: orderItem.productId,
                name: orderItem.productName || '商品',
                attributes: orderItem.productVariant || '默认规格',
                price: orderItem.price || 0,
                quantity: orderItem.quantity || 1,
                image: orderItem.productImage || orderData.items?.mainImage || 'https://images.unsplash.com/photo-1551717743-49959800b1f6',
              };
            }
          }

          // 如果找不到目标商品，则使用默认商品信息
          if (!targetProduct && orderData.items) {
            targetProduct = {
              id: orderData.items.productId || 0,
              name: orderData.items.name || '商品',
              attributes: orderData.items.description || '默认规格',
              price: orderData.items.price || 0,
              quantity: 1,
              image: orderData.items.mainImage || 'https://images.unsplash.com/photo-1551717743-49959800b1f6',
            };
          }

          // 更新订单信息
          orderInfo.value = {
            orderId: orderData.orderId,
            storeName: orderData.storeName || '商家店铺',
            orderItemId: orderItemId || (orderData.orderItems && orderData.orderItems.length > 0 ? orderData.orderItems[0].orderItemId : 0),
            products: targetProduct ? [targetProduct] : [{
              id: productId || (orderData.items?.productId || 0),
              name: '商品',
              attributes: '默认规格',
              price: 0,
              quantity: 1,
              image: 'https://images.unsplash.com/photo-1551717743-49959800b1f6',
            }]
          };

          console.log('处理后的订单信息:', orderInfo.value);
        } else {
          showToast('获取订单信息失败');
        }
      } catch (error) {
        console.error('获取订单详情失败:', error);
        showToast('获取订单详情失败');
      }
    };

    // 设置评分
    const setRating = (value) => {
      rating.value = value;
    };

    // 获取评分文字描述
    const getRatingText = () => {
      const texts = ['差评', '较差', '一般', '不错', '非常好'];
      return texts[rating.value - 1];
    };

    // 上传图片
    const uploadImage = () => {
      if (images.value.length >= 5) {
        showToast('最多上传5张图片');
        return;
      }

      // 触发文件选择器
      fileInput.value.click();
    };

    // 文件输入变化处理
    const handleFileChange = (event) => {
      const file = event.target.files[0];
      if (!file) return;

      // 验证文件类型
      if (!file.type.includes('image/')) {
        showToast('请选择图片文件');
        return;
      }

      // 验证文件大小，限制为5MB
      if (file.size > 5 * 1024 * 1024) {
        showToast('图片大小不能超过5MB');
        return;
      }

      // 创建文件阅读器
      const reader = new FileReader();
      reader.onload = (e) => {
        // 将图片添加到数组
        images.value.push(e.target.result);
        showToast('图片上传成功');
      };

      // 读取文件为DataURL
      reader.readAsDataURL(file);

      // 重置文件输入，以便可以选择相同的文件
      event.target.value = '';
    };

    // 删除图片
    const deleteImage = (index) => {
      images.value.splice(index, 1);
    };

    // 验证评价有效性
    const isReviewValid = computed(() => {
      return content.value.length >= 5 && rating.value > 0;
    });

    // 提交评价
    const submitReview = async () => {
      if (!isReviewValid.value) {
        showToast('请至少输入5个字的评价内容');
        return;
      }

      try {
        // 获取用户信息
        let userId = null;
        try {
          const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
          userId = userInfo.data?.userId || userInfo.userId;
        } catch (e) {
          console.error('解析用户信息失败:', e);
        }

        if (!userId) {
          showToast('用户信息获取失败，请重新登录');
          return;
        }

        const reviewData = {
          orderId: Number(orderId),
          orderItemId: orderInfo.value.orderItemId,
          productId: productId || orderInfo.value.products[0].id,
          userId: userId,
          rating: averageRating.value, // 使用平均分
          content: content.value,
          images: images.value.join(','), // 将图片数组转为逗号分隔的字符串
          createdAt: new Date().toISOString().split('T')[0] // 当前日期，格式：YYYY-MM-DD
        };

        console.log('提交评价数据:', reviewData);

        // 调用后端API添加评价
        const response = await api.addProductReview(reviewData.productId, reviewData);
        if (response && response.code === 100) {
          // 更新订单项的评价状态为已评价
          try {
            const updateData = {
              orderItemId: reviewData.orderItemId,
              isReviewed: 1
            };

            // 添加检查并打印日志
            console.log('准备更新订单项状态，数据:', updateData);

            // 确保orderItemId存在且有效
            if (!updateData.orderItemId) {
              console.warn('订单项ID不存在，跳过更新状态');
              // 不抛出异常，继续流程
            } else {
              const updateResponse = await api.updateOrderItem(updateData);

              // 修改判断逻辑，兼容两种响应结构
              if ((updateResponse?.data?.code === 100) || (updateResponse?.code === 100)) {
                console.log('更新订单项评价状态成功');
              } else {
                console.warn('更新订单项评价状态返回异常结果:', updateResponse);
                // 即使状态更新失败，也不阻止评价成功提示
              }
            }
          } catch (error) {
            // 改进错误处理
            const errorMessage = error ? (error.message || JSON.stringify(error)) : 'undefined error';
            console.error('更新订单项评价状态失败:', errorMessage);
            // 不阻止主流程继续
          }

          showToast('评价提交成功');

          // 使用路由直接跳转，不使用定时器
          router.replace('/orders');
        } else {
          showToast(response?.data?.message || response?.message || '提交评价失败');
        }
      } catch (error) {
        console.error('提交评价失败:', error);
        showToast('提交评价失败，请稍后再试');
      }
    };

    // 创建文件输入引用
    const fileInput = ref(null);

    onMounted(() => {
      fetchOrderDetail();
    });

    // 组件卸载前清理任何可能的定时器
    onBeforeUnmount(() => {
      if (redirectTimer) {
        clearTimeout(redirectTimer);
        redirectTimer = null;
      }
    });

    return {
      orderInfo,
      rating,
      logisticsRating,
      sellerRating,
      content,
      images,
      isAnonymous,
      fileInput,
      hasReviewed,
      averageRating,
      setRating,
      getRatingText,
      uploadImage,
      handleFileChange,
      deleteImage,
      isReviewValid,
      submitReview
    };
  }
});
</script>

<style scoped>
.review-container {
  background-color: #f8fafc;
  min-height: 100vh;
  padding-bottom: 80px;
}

.navbar {
  display: flex;
  align-items: center;
  padding: 10px 16px;
  background-color: white;
  position: relative;
  z-index: 10;
}

.navbar-back {
  color: #4a5568;
  font-size: 16px;
  padding: 5px;
}

.navbar-title {
  flex: 1;
  text-align: center;
  font-size: 17px;
  font-weight: 500;
  margin: 0 10px;
}

.store-info {
  background-color: white;
  padding: 15px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #e2e8f0;
}

.store-icon {
  color: #3490dc;
  margin-right: 10px;
  font-size: 16px;
}

.product-container {
  background-color: white;
  padding: 15px;
  margin-bottom: 10px;
}

.product-card {
  display: flex;
  padding: 10px 0;
}

.product-image {
  width: 60px;
  height: 60px;
  border-radius: 5px;
  object-fit: cover;
  margin-right: 10px;
}

.product-details {
  flex: 1;
}

.product-name {
  font-size: 14px;
  margin-bottom: 5px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  height: 40px;
}

.product-attr {
  font-size: 12px;
  color: #718096;
  margin-bottom: 5px;
}

.product-price-qty {
  font-size: 12px;
  display: flex;
  justify-content: space-between;
}

.price {
  font-weight: 500;
}

.quantity {
  color: #718096;
}

.rating-container,
.service-rating,
.review-content,
.upload-container,
.anonymous-container {
  background-color: white;
  padding: 15px;
  margin-bottom: 10px;
}

.rating-header,
.service-title,
.content-header,
.upload-header {
  font-weight: 500;
  margin-bottom: 15px;
  font-size: 15px;
}

.rating-stars,
.service-stars {
  display: flex;
  align-items: center;
}

.rating-stars .fas,
.service-stars .fas {
  font-size: 24px;
  margin-right: 5px;
  color: #cbd5e0;
  cursor: pointer;
}

.rating-stars .fas.active,
.service-stars .fas.active {
  color: #f6ad55;
}

.rating-text {
  margin-left: 10px;
  font-size: 14px;
  color: #4a5568;
}

.content-textarea {
  width: 100%;
  height: 120px;
  border: 1px solid #e2e8f0;
  border-radius: 5px;
  padding: 10px;
  font-size: 14px;
  resize: none;
}

.content-count {
  text-align: right;
  font-size: 12px;
  color: #a0aec0;
  margin-top: 5px;
}

.upload-grid {
  display: flex;
  flex-wrap: wrap;
  margin: 10px -5px;
}

.image-item,
.upload-btn {
  width: 80px;
  height: 80px;
  margin: 5px;
  position: relative;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 5px;
}

.delete-btn {
  position: absolute;
  top: -8px;
  right: -8px;
  width: 20px;
  height: 20px;
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.upload-btn {
  border: 1px dashed #cbd5e0;
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.upload-btn i {
  font-size: 24px;
  color: #a0aec0;
  margin-bottom: 5px;
}

.upload-text {
  font-size: 12px;
  color: #a0aec0;
}

.upload-tip {
  font-size: 12px;
  color: #a0aec0;
  margin-top: 5px;
}

.anonymous-switch {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.anonymous-tip {
  font-size: 12px;
  color: #a0aec0;
}

/* 开关样式 */
.switch {
  position: relative;
  display: inline-block;
  width: 50px;
  height: 24px;
}

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  transition: .4s;
  border-radius: 24px;
}

.slider:before {
  position: absolute;
  content: "";
  height: 20px;
  width: 20px;
  left: 2px;
  bottom: 2px;
  background-color: white;
  transition: .4s;
  border-radius: 50%;
}

input:checked+.slider {
  background-color: #3490dc;
}

input:checked+.slider:before {
  transform: translateX(26px);
}

.submit-container {
  padding: 20px 15px;
}

.submit-btn {
  width: 100%;
  padding: 12px;
  border: none;
  background-color: #3490dc;
  color: white;
  font-size: 16px;
  font-weight: 500;
  border-radius: 5px;
  cursor: pointer;
}

.submit-btn:disabled {
  background-color: #a0aec0;
  cursor: not-allowed;
}
</style>